package com.compass.doctor.ui.setting

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.compass.doctor.R
import com.compass.doctor.databinding.ActivitySettingBinding

import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.setting.viewmodel.SettingViewModel
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.ui.MainViewModel
import com.compass.doctor.ui.login.LoginActivity
import com.compass.framework.constant.POLICY
import com.compass.framework.constant.SERVICE
import com.compass.framework.dialog.LogoutTipsDialog
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.manager.ActivityManager
import com.compass.framework.manager.AppManager
import com.compass.framework.manager.AppManager.getAppVersionCode
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.manager.FileManager
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.UpdateInfo
import com.compass.framework.toast.TipsToast
import com.compass.framework.update.manager.DownloadManager
import com.compass.framework.utils.ViewUtils
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.netease.yunxin.kit.chatkit.ui.custom.ChatConfigManager
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.login.LoginCallback
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 设置界面
 */

class SettingActivity : BaseVBActivity<ActivitySettingBinding>() {
    companion object {
        fun start(context: Context) {
            val intent = Intent(context, SettingActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val settingViewModel: SettingViewModel by viewModels()
    private var allCacheDir = arrayOfNulls<String>(2)
    private val mainViewModel: MainViewModel by viewModels()

    override fun initView(savedInstanceState: Bundle?) {

        mBinding.tvCurrentVersion.text = String.format(
            getString(
                R.string.setting_current_version
            ), AppManager.getAppVersionName(this)
        )
        if (UserInfoManager.isLogin()) {
            mBinding.tvLogout.visible()
        } else {
            mBinding.tvLogout.gone()
        }
        val rootDir = FileManager.getAppRootDir()
        val imageDir = FileManager.getImageDirectory(this)
        allCacheDir = arrayOf(rootDir, imageDir.absolutePath)
        lifecycleScope.launch(Dispatchers.IO) {
            updateCacheSize()
        }

    }

    override fun initData() {
        mBinding.messageReadSc.isChecked = settingViewModel.getShowReadStatus()
        mainViewModel.versionLiveData.observe(this) {
            it?.let { updateInfo ->
                if (updateInfo.versionCode <= getAppVersionCode(this)) {
                    showToast("已是最新版")
                    mBinding.tvCheckVersion.text = "已是最新版本"
                } else {
                    updateTest(updateInfo)
                }
            }

        }
        mainViewModel.signOutLiveData.observe(this) {
            it?.let {
                out()
            }
        }
    }

    /**
     * 更新缓存大小
     */
    private fun updateCacheSize() {
        lifecycleScope.launch {
            val size = FileManager.getTotalCacheSize(this@SettingActivity, *allCacheDir)
            mBinding.tvCache.text = size
        }
    }

    override fun intListener() {
        mBinding.messageReadSc.onClick {
            val checked: Boolean = mBinding.messageReadSc.isChecked
            settingViewModel.setShowReadStatus(checked)
            ChatConfigManager.showReadStatus = checked
        }

        mBinding.clCurrentVersion.onClick {
            mainViewModel.getAppVersion()

        }
        mBinding.clPrivacyPolicy.onClick {
            WebDetailActivity.start(
                this@SettingActivity, POLICY,
                "隐私政策"
            )
        }
        mBinding.notifyFl.onClick {

            SettingNotifyActivity.start(this@SettingActivity)
        }

        mBinding.clClearCache.onClick {
            showClearCacheDialog()
        }
        mBinding.tvSignOut.onClick {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("注销账号后，您的数据将被一并删除切无法恢复，是否继续注销？")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    mainViewModel.signOut()
                    it?.dismiss()
                }.create().show()
        }

        mBinding.clUserAgreement.onClick {
            WebDetailActivity.start(
                context = this@SettingActivity,
                url = SERVICE,
                title = "服务协议"
            )
        }

        mBinding.tvLogout.onClick {

            LogoutTipsDialog.Builder(this, mButtonClickListener = {
                showLoading()
                IMKitClient.logoutIM(object : LoginCallback<Void> {
                    override fun onError(errorCode: Int, errorMsg: String) {
                        TipsToast.showTips(errorMsg)
                        dismissLoading()
                    }

                    override fun onSuccess(data: Void?) {
                        out()
                    }

                })

            }).show()
        }
    }

    private fun out() {
        UserInfoManager.clearUserInfo()
        DictionariesManager.clearInfo()
        dismissLoading()
        ActivityManager.finishOtherActivity(SettingActivity::class.java)
        LoginActivity.start(this@SettingActivity)
        finish()
    }

    private val apkName = "medical.apk"
    private var manager: DownloadManager? = null
    private fun updateTest(updateInfo: UpdateInfo) {
        manager = DownloadManager.Builder(this).run {
            apkUrl(updateInfo.url)
            apkName(apkName)
            smallIcon(R.mipmap.ic_logo)
            //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
            apkVersionCode(updateInfo.versionCode)
            //同时下面三个参数也必须要设置
            apkVersionName(updateInfo.apkVersionName)
            apkSize(updateInfo.apkSize)
            apkDescription(updateInfo.apkDescription)
                .apkMD5("")
            //省略一些非必须参数...
            build()
        }
        manager?.download()
    }

    /**
     * 清理缓存弹框
     */
    private fun showClearCacheDialog() {
        CommonMessageDialog.Builder(this)
            .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
            .setMessage(getStringFromResource(R.string.setting_clear_cache_tips))
            .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

            .setCancel(getString(com.compass.framework.R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                clearCache()
                it?.dismiss()
            }.create().show()
    }

    /**
     * 清理缓存
     */
    private fun clearCache() {
        showLoading("正在清理...")
        lifecycleScope.launch {
            allCacheDir.forEach { filesDir ->
                filesDir?.let { FileManager.delAllFile(it) }
            }
            delay(500)
            dismissLoading()
            updateCacheSize()
        }
    }
}